from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from apps.models import Comment
from apps.serializers.Comment import CommentSerializer, CommentDeleteSerializer
from apps.utils.common_mixin import APIDeleteModelMixin, APICreateModelMixin
from apps.utils.common_response import APIResponse
from rest_framework.mixins import CreateModelMixin, DestroyModelMixin


# 根据id号来判定是哪一个的评论区
class CommentListView(GenericViewSet, CreateModelMixin):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    authentication_classes = []
    permission_classes = []

    def list(self, request, *args, **kwargs):
        userId = request.GET.get("userId", None)
        thingId = request.GET.get("thingId", None)
        # 排序
        order = request.GET.get("order", 'recent')
        # 默认以评论时间优先，否则以点赞数优先
        if thingId or userId:
            if order == 'recent':
                orderBy = '-comment_time'
            else:
                orderBy = 'like_count'
            # 反关联thing的信息,提升性能和响应速度
            if thingId:
                comments = Comment.objects.select_related("thing").filter(thing=thingId).order_by('-like_count')
                # many = True参数告诉序列化器输入的数据是一个对象列表，而不是单个对象
            elif userId:
                comments = Comment.objects.filter(user=userId).order_by(orderBy)
            serializer = CommentSerializer(comments, many=True)
            return APIResponse(msg='查询成功', data=serializer.data)
        else:
            return APIResponse(code=1, msg='thingId或userId不能为空')


class CommentDeleteView(GenericViewSet,APICreateModelMixin,APIDeleteModelMixin):
    queryset = Comment.objects.all()
    serializer_class = CommentDeleteSerializer

    # 新增评论 方法二
    # def create(self, request, *args, **kwargs):
    #     print(request.data)
    #     serializer = CommentDeleteSerializer(data=request.data)
    #     if serializer.is_valid():
    #         serializer.save()
    #         return APIResponse(msg='新增成功', data=serializer.data)



class CommentLike(GenericViewSet):
    def create(self,request):
        try:
            commentId = request.GET.get('commentId')
            comment = Comment.objects.get(pk=commentId)
            if commentId:
                if comment.like_count >=1:
                    return APIResponse(msg='已经点过赞啦~')
                comment.like_count += 1
                comment.save()
            serializer = CommentSerializer()
            # serializer.is_valid(raise_exception=True)
            return APIResponse(msg='点赞成功', data=serializer.data)
        except Comment.DoesNotExist:
            return APIResponse(code=1, msg='对象不存在')

